/**
 * Created by wxb on 2017/10/19.
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.theme.components')
    .controller('VideoUploadNewCtrl', VideoUploadNewCtrl);

  /** @ngInject */
  function VideoUploadNewCtrl($scope, $qupload, $log, qiniuToken, rfc4122, $uibModal) {
    var token, videoBaseUrl;

    qiniuToken.osgVideoToken().then(function (data) {
      token = data.data.token;
    });
    qiniuToken.osgVideoBaseUrl().then(function (data) {
      videoBaseUrl = data;
      $scope.videoObj.videoBaseUrl = videoBaseUrl;
    });

    $scope.videoObj.videoSelectFiles = $scope.videoObj.videoSelectFiles || [];

    var start = function (index) {
      $scope.videoObj.videoSelectFiles[index].progress = {
        p: 0
      };
      $scope.videoObj.videoSelectFiles[index].config = {
        key: $scope.videoObj.key + rfc4122.v4() + '.' + $scope.videoObj.videoSelectFiles[index].file.name.split(".").pop(),
        file: $scope.videoObj.videoSelectFiles[index].file,
        token: token
      };
      $scope.videoObj.videoSelectFiles[index].upload = $qupload.upload($scope.videoObj.videoSelectFiles[index].config);
      $scope.videoObj.videoSelectFiles[index].upload.then(function (response) {
        $log.info(response);
        $scope.videoObj.videoSelectFiles[index].videoUrl = videoBaseUrl + response.key;
        $scope.videoObj.videoSelectFiles[index].uploadVideoUrl = response.key;
        $scope.videoObj.callback(index);
      }, function (response) {
        $log.info(response);
      }, function (evt) {
        $scope.videoObj.videoSelectFiles[index].progress.p = Math.floor(100 * evt.loaded / evt.totalSize);

      });
    };

    $scope.videoObj.start = start;

    $scope.videoAbort = function (index) {
      $scope.videoObj.videoSelectFiles[index].upload.abort();
      $scope.videoObj.videoSelectFiles.splice(index, 1);
      $scope.videoProgressbarValue = undefined;
    };

    $scope.onFileSelect = function ($files) {
      console.log($files);
      if ($files.length > 0) {
        var modalInstance = $uibModal.open({
          animation: true,
          templateUrl: 'app/theme/components/videoUploadNew/modal/setVideo.html',
          controller: 'SetVideoModalCtrl'
        });

        modalInstance.result.then(function (formData) {
          var offsetx = $scope.videoObj.videoSelectFiles.length;
          for (var i = 0; i < $files.length; i++) {
            $scope.videoObj.videoSelectFiles[i + offsetx] = {
              file: $files[i],
              videoTitle: formData.title,
              videoDesc: formData.desc,
              videoSurface: formData.videoSurface,

            };
            start(i + offsetx);
          }
        });
      }
    };


  }

})();










